package com.onadake.web.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import javax.annotation.PostConstruct;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.stereotype.Service;

/**
 * Implements request service with simple URL.
 * Target in this case means web service host. 
 * 
 * @author radek.hecl
 *
 */
@Service
public class URLRequestService implements RequestService {

    /**
     * Builder object.
     */
    public static class Builder {
        
        /**
         * Builds the result object.
         * 
         * @return this instance
         */
        public URLRequestService build() {
            return new URLRequestService(this);
        }
    }
    
    /**
     * Constructor to allow frameworks create new instances.
     */
    @SuppressWarnings("unused")
    private URLRequestService() {
    }
    
    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public URLRequestService(Builder builder) {
        guardInvariants();
    }
    
    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    @PostConstruct
    private void guardInvariants() {
        
    }
    
    @Override
    public String request(String target, String data) {
        OutputStreamWriter wr = null;
        BufferedReader rd = null;
        try {
            URL url = new URL(target);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            String res = "";
            while ((line = rd.readLine()) != null) {
                res += line;
            }
            wr.close();
            rd.close();
            return res;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(wr);
            IOUtils.closeQuietly(rd);
        }

    }
    
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
